<template>
    <a-modal :keyboard="false" :maskClosable="false" title="陪护服务" :open="visible" :width="550" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical" ref="formRef" :model="modelRef">
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="医院"
                        name="projectCode"
                        :rules="[
                            {
                                required: true,
                                message: '请选择医院',
                            },
                        ]"
                    >
                        <a-select v-model:value="modelRef.projectCode">
                            <a-select-option v-for="item in treeData" :key="item.code" :value="item.code">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="陪护服务名称"
                        name="typeId"
                        :rules="[
                            {
                                required: true,
                                message: '请输入陪护服务名称',
                            },
                        ]"
                    >
                        <a-select v-model:value="modelRef.typeId">
                            <a-select-option v-for="item in cateList" :key="item.id" :value="item.id">{{ item.name }}</a-select-option>
                        </a-select>
                    </a-form-item>
                </a-col>

                <a-col :xs="24" :sm="24" :md="24">
                    <a-space v-for="(sight, index) in modelRef.types" :key="index" style="display: flex; margin-bottom: 8px" align="baseline">
                        <a-form-item
                            :name="['types', index, 'name']"
                            label="类型名称"
                            :rules="{
                                required: true,
                                message: '请输入类型名称',
                            }"
                        >
                            <a-input v-model:value="sight.name" placeholder="请输入类型名称"></a-input>
                        </a-form-item>
                        <a-form-item
                            label="价格"
                            :name="['types', index, 'price']"
                            :rules="{
                                required: true,
                                message: '请输入价格',
                            }"
                        >
                            <a-input v-model:value="sight.price" placeholder="元/天" />
                        </a-form-item>
                        <MinusCircleOutlined @click="removeSight(sight, index)" />
                    </a-space>
                    <!-- <PlusCircleOutlined @click="addSight(sight)" color="#1677ff" /> -->
                    <a-button type="primary" size="small" @click="addSight(sight)" style="margin-bottom: 20px;">添加类型</a-button>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="是否线上付款" v-bind="validateInfos.paymentOnline">
                        <a-radio-group v-model:value="modelRef.paymentOnline">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="12">
                    <a-form-item label="是否显示" v-bind="validateInfos.display">
                        <a-radio-group v-model:value="modelRef.display">
                            <a-radio :value="1">是</a-radio>
                            <a-radio :value="0">否</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, computed } from 'vue';
    import { Form, message } from 'ant-design-vue';
    import { cloneDeep, isUndefined, isArray } from 'lodash-es';
    import { getMedicalCaregiverService, createMedicalCaregiverService, updateMedicalCaregiverService } from '@/api/companion/home';
    import { getList } from '@/api/companion/cate';
    import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const formRef = ref<any>(null);
            const defaultForm = {
                projectCode: '',
                display: 1,
                paymentOnline: 1,
                types: [
                    {
                        name: '',
                        price: '',
                    },
                ],
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            const rulesRef = reactive({
                name: [{ required: true, message: '请输入陪护服务名称' }],
                fileList: [{ required: true, message: '请上传上传宣传图', type: 'array' }],
                paymentOnline: [{ required: true, message: '请选择是否线上付款' }],
                display: [{ required: true, message: '请选择是否显示' }],
            });
            const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);
            const cateList = ref<any[]>([]);
            // 记录初始值
            const initValues = reactive({});
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(async () => {
                if (props.visible) {
                    if (props.model) {
                        Object.assign(modelRef, props.model);
                        console.log(props.model);

                        getList().then(res => {
                            cateList.value = res.data || [];
                        });

                        if (!isUndefined(modelRef.id)) {
                            getMedicalCaregiverService(modelRef.id).then(async res => {
                                const { serviceTypeDTOList: types, ...last } = res.data;
                                Object.assign(modelRef, last, {
                                    types,
                                });
                            });
                        }
                    }
                }
            });

            const addSight = () => {
                modelRef.types.push({
                    name: '',
                    price: '',
                });
            };

            const removeSight = (data, index) => {
                modelRef.types.splice(index, 1);
            };

            const handleCancel = () => {
                formRef.value.resetFields();
                emit('cancel');
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));
            };

            const handleSubmit = async () => {
                formRef.value.validate().then(res => {
                    loading.value = true;
                    const { fileList = [], ...params } = modelRef;
                    if (fileList.length > 0) {
                        params.advertisingImage = fileList[0];
                    }

                    (isUndefined(modelRef.id) ? createMedicalCaregiverService : updateMedicalCaregiverService)(params)
                        .then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };

            const treeData = computed(() => {
                if (isArray(modelRef.treeData) && modelRef.treeData.length > 0) return modelRef.treeData[0].children;
                return [];
            });
            return {
                loading,
                formRef,
                modelRef,
                handleSubmit,
                handleCancel,
                validateInfos,
                initValues,
                addSight,
                removeSight,
                cateList,
                treeData,
            };
        },
        components: {
            MinusCircleOutlined,
            PlusCircleOutlined,
        },
    });
</script>
